#include "myserver.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonValue>

MyServer::MyServer(QObject *parent) : QObject(parent)
{
    server = new QTcpServer;

    connect(server, &QTcpServer::newConnection,
            this, &MyServer::serverNewConnectionSlot);
}

MyServer::~MyServer()
{
    stopServer();
}

MyServer *MyServer::getObject()
{
    static MyServer ms;
    return &ms;
}

bool MyServer::startServer(quint16 port)
{
    if(server->isListening())
        stopServer();
    bool ok = server->listen(QHostAddress::Any, port);
    if(ok)
    {
        qDebug() << "服务器启动成功！监听端口：" << port;
    }
    else
    {
        qDebug() << "服务器启动失败。";
    }
    return ok;
}

void MyServer::stopServer()
{
    //断开所有客户端
    for(int i = 0; i < clientList.length(); i++)
    {
        disconnect(clientList.at(i)->socket, 0, 0, 0);      //断开所有信号与槽
        clientList.at(i)->socket->disconnectFromHost();     //断开与客户端的连接
        delete clientList.at(i);                            //销毁对象
    }
    //清空客户端列表
    clientList.clear();
    //停止监听
    if(server->isListening())
        server->close();
    qDebug() << "服务器停止服务，所有的客户端均已断开";
}

QJsonArray MyServer::getClientList()
{
    QJsonArray arr;
    for(int i = 0; i < clientList.length(); i++)
    {
        QJsonObject obj;
        obj.insert("index", static_cast<qint32>(clientList.at(i)->index));
        obj.insert("ip", clientList.at(i)->ip);
        obj.insert("port", static_cast<qint16>(clientList.at(i)->port));
        arr.append(obj);
    }
    return arr;
}

int MyServer::getClientCount()
{
    return clientList.length();
}

bool MyServer::getServerState()
{
    return server->isListening();
}

void MyServer::sendDataToClient(int index, const QByteArray &data)
{
    for(int i = 0; i < clientList.length(); i++)
    {
        if(index == static_cast<int>(clientList.at(i)->index))
        {
            clientList.at(i)->socket->write(data);
            return;
        }
    }
}

void MyServer::sendDataToClient(int index, const QJsonObject &data)
{
    sendDataToClient(index, QJsonDocument(data).toJson());
}

void MyServer::sendDataToClient(int index, const QJsonDocument &data)
{
    sendDataToClient(index, data.toJson());
}

void MyServer::sendDataToAllClient(const QByteArray &data)
{
    for(int i = 0; i < clientList.length(); i++)
    {
        clientList.at(i)->socket->write(data);
    }
}

void MyServer::sendDataToAllClient(const QJsonObject &data)
{
    sendDataToAllClient(QJsonDocument(data).toJson());
}

void MyServer::sendDataToAllClient(const QJsonDocument &data)
{
    sendDataToAllClient(data.toJson());
}

void MyServer::serverNewConnectionSlot()
{
    QTcpSocket *socket = server->nextPendingConnection();
    Client *client = new Client;
    client->socket = socket;
    client->ip = socket->peerAddress().toString();
    client->port = socket->peerPort();
    client->index = nowIndex++;
    clientList.append(client);

    connect(socket, &QTcpSocket::disconnected,
            this, &MyServer::socketDisconnectedSlot);
    connect(socket, &QTcpSocket::readyRead,
            this, &MyServer::socketReadyReadSlot);

    qDebug() << "新客户端连接，现有客户端数量：" << clientList.length();
}

void MyServer::socketDisconnectedSlot()
{
    //找到谁断开了
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    //销毁对象
    for(int i = 0; i < clientList.length(); i++)
    {
        if(socket == clientList.at(i)->socket)
        {
            delete clientList.at(i);
            clientList.removeAt(i);
            qDebug() << "客户端断开，现有客户端数量：" << clientList.length();
            return;
        }
    }

}

void MyServer::socketReadyReadSlot()
{
    //找到谁发送的信息了
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    QByteArray data;
    while (socket->bytesAvailable()) {
        data.append(socket->readAll());
    }
    for(int i = 0; i < clientList.length(); i++)
    {
        if(socket == clientList.at(i)->socket)
        {
            clientList.at(i)->data.append(QString::fromLocal8Bit(data));
            handleData(clientList.at(i)->index);
            return;
        }
    }

}

void MyServer::handleData(quint32 index)
{
    for(int cli = 0; cli < clientList.length(); cli++)
    {
        if(index == clientList.at(cli)->index)
        {
            //循环判断data数据是否是一个完整的json
            int count = 0;      //括号的数量
            for(int i = 0; i < clientList.at(cli)->data.length(); i++)
            {
                if(count == 0)
                {
                    //要求data以{开头
                    if(clientList.at(cli)->data.at(i) != "{")
                    {
                        clientList.at(cli)->data = clientList.at(cli)->data.mid(
                                    1, clientList.at(cli)->data.length() - 1);
                        i--;
                        continue;
                    }
                }
                if(clientList.at(cli)->data.at(i) == "{")
                    count++;
                else if(clientList.at(cli)->data.at(i) == "}")
                    count--;
                if(count == 0)
                {
                    QString newData = clientList.at(cli)->data.left(i + 1);
                    //newData 就是完整的一个Json数据
                    emit receiveDataFromClient(index, QJsonDocument::fromJson(newData.toLocal8Bit()).object());
                    clientList.at(cli)->data = clientList.at(cli)->data.mid(
                                i+1, clientList.at(cli)->data.length() - 1);
                    i = -1;
                }
            }
            return;
        }
    }
}
